package com.hefan.api.service.live;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.bean.Message;
import com.hefan.common.ons.service.ONSProducer;
import com.hefan.common.util.DynamicProperties;
import com.hefan.common.util.MapUtils;
import com.hefan.live.bean.*;
import com.hefan.live.itf.LiveLogService;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.notify.bean.PushMqVo;
import com.hefan.user.bean.WebUser;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by nigle on 2016/9/27.
 */
@Component
public class LiveLogLocalService {

	public Logger logger = LoggerFactory.getLogger(LiveLogLocalService.class);
    @Reference
    LiveLogService liveLogService;
	@Reference
	ONSProducer onsProducer;
	@Reference
	LivingRedisOptService livingRedisOptService;

    public LiveLog getLiveLogByUuid(String liveUuid){
        return liveLogService.getLiveLogByUuid(liveUuid);
    }

    public boolean liveStartOperate(LiveRoom liveRoom, LiveLog liveLog) {
		try {
			liveLogService.liveStartOperate(liveRoom,liveLog);
		}catch (Exception d){
			return false;
		}
		return true;
    }

    /**
     * 下单后更新直播盒饭收入（包含虚拟）
     * ticket_count
     * false_ticket_count
     * @param liveLog
     */
    public int updateLiveLogForRebalance(LiveLog liveLog){return liveLogService.updateLiveLogForRebalance(liveLog);}

    public LiveLog liveEndOperate(LiveLog liveLog) {return liveLogService.liveEndOperate(liveLog);}
    
	/**
	 * 用户进入直播间更新观看人数，直播结束时取
	 */
	public int changeWatchNum(String liveUuid, int chatRoomId, int addNum) {
		return liveLogService.changeWatchNum(liveUuid, chatRoomId, addNum);
	}

	/**
	 * 获取直播推拉流地址
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map getLiveUrls(String liveUuid) {
		Map map = new HashMap<>();
		// 推流地址
		StringBuilder pushUrls = new StringBuilder();
		// 阿里运营商
		String aliPushUrl = DynamicProperties.getString("ali.push.domain.pre") + liveUuid
				+ DynamicProperties.getString("ali.push.domain.suf");
		// 虹视云运营商
		String hongPushUrl = DynamicProperties.getString("hong.push.domain.pre") + liveUuid;
		pushUrls.append(aliPushUrl);
		pushUrls.append(",");
		pushUrls.append(hongPushUrl);

		// 拉流地址
		StringBuilder pullUrls = new StringBuilder();
		// 阿里运营商
		String aliPullUrl = DynamicProperties.getString("ali.pull.domain") + liveUuid;
		// 虹视云运营商
		String hongPullUrl = DynamicProperties.getString("hong.pull.domain") + liveUuid;
		pullUrls.append(aliPullUrl);
		pullUrls.append(",");
		pullUrls.append(hongPullUrl);

		map.put("pushUrls", pushUrls.toString());
		map.put("pullUrls", pullUrls.toString());
		return map;
	}

	/**
	 * 开播后执行的一些异步操作
	 * 开播进机器人MQ发送
	 * 初始化心跳数据
	 * 推送开播提醒
	 * @param liveLog
	 * @param user
     */
	@Async
	public void doPush(LiveLog liveLog, WebUser user) {
		String onsEnv = DynamicProperties.getString("ons.env");

		//开播进入机器人MQ发送
		try {
			Message message = new Message();
			RobotListenerVo robotListenerVo = new RobotListenerVo();
			robotListenerVo.setAnchId(liveLog.getUserId());
			robotListenerVo.setLiveUuid(liveLog.getLiveUuid());
			robotListenerVo.setChatRoomId(liveLog.getChatRoomId());
			message.put("vo", JSON.toJSONString(robotListenerVo));
			message.setTopic(TopicRegistry.HEFAN_ROBOT_WHEN_START);
			message.setTag(onsEnv);
			onsProducer.sendMsg(message);
			logger.info("发送MQ：{}直播间初始化加入机器人成功",liveLog.getUserId());
		} catch (Exception e) {
			logger.info("发送MQ：{}直播间初始化加入机器人失敗！",liveLog.getUserId());
		}

		// 心跳数据初始化 嘭嘭
		LivingHeartBeatVo livingHeartBeatVo = new LivingHeartBeatVo();
		livingHeartBeatVo.setLiveUuid(liveLog.getLiveUuid());
		livingHeartBeatVo.setChatRoomId(liveLog.getChatRoomId());
		livingHeartBeatVo.setAuthoruserId(liveLog.getUserId());
		livingHeartBeatVo.setUpdateTime(System.currentTimeMillis());
		livingRedisOptService.initLivingHeartBeatInfo(livingHeartBeatVo.getLiveUuid(),
				JSON.toJSONString(livingHeartBeatVo));
		logger.info("心跳初始化:", JSON.toJSONString(livingHeartBeatVo));

		//发送推送开播提醒---开始
		Map urlMap = getLiveUrls(liveLog.getLiveUuid());
		String pullUrls = MapUtils.getStrValue(urlMap,"pullUrls","");
		LivingRoomInfoVo lriVo = new LivingRoomInfoVo();
		lriVo.setHeadImg(user.getHeadImg());// 主播头像
		lriVo.setLiveUuid(liveLog.getLiveUuid());// 直播uuid
		lriVo.setName(user.getNickName());// 主播昵称
		lriVo.setChatRoomId(liveLog.getChatRoomId());// 聊天室id
		lriVo.setLiveUrl(liveLog.getPullUrl());// 拉流地址
		lriVo.setPersonSign(liveLog.getLiveName());// 直播名
		lriVo.setId(liveLog.getUserId());// 主播id
		lriVo.setUserId(liveLog.getUserId());// 主播id
		lriVo.setType(user.getUserType());// 主播类型
		lriVo.setLiveImg(liveLog.getLiveImg());// 直播间封面
		lriVo.setDisplayGraph(liveLog.getDisplayGraph());// 点亮样式
		lriVo.setLocation(StringUtils.isNotBlank(liveLog.getLocation()) ? liveLog.getLocation(): GlobalConstants.DEFAULT_LOCATION);
		lriVo.setHefanTotal(String.valueOf(user.getHefanTotal()));//主播盒饭数
		lriVo.setPullUrls(pullUrls);//拉流地址
		lriVo.setStartLiveTime(System.currentTimeMillis());//开播时间，用于列表排序
		PushMqVo pushMqVo = new PushMqVo();
		pushMqVo.setNickName(user.getNickName());
		pushMqVo.setUserId(user.getUserId());
		pushMqVo.setType(1);
		pushMqVo.setLivingRoomInfoVo(lriVo);
		try {
			Message messagePush = new Message();
			messagePush.put("pushMqVo", JSON.toJSONString(pushMqVo));
			messagePush.setTopic(TopicRegistry.HEFANTV_PUSH);
			messagePush.setTag(onsEnv);
			onsProducer.sendMsg(messagePush);
			logger.info("开播提醒队列消息发送成功"+liveLog.getLiveUuid());
		} catch (Exception e) {
			logger.info("开播提醒队列消息发送失敗"+liveLog.getLiveUuid());
		}
		//初始化最后进入直播间时间数据
		livingRedisOptService.addLastJoinTime(liveLog.getLiveUuid());
	}
}
